import { message } from 'antd';
import { makeObservable, action, runInAction } from 'mobx';

import Obverse from './obverse';
import useIpcSend, { TypeKey } from '@/hooks/useIpcSend';
import { GetPrintOption, DefaultPrinterConfig, OriginPrint } from '@/type';
import {
    getPrinterList,
    printFile,
    cleanCache,
    getCachePath,
    getSupportPrintType
} from '@/request/api/home';

export type PrintOption = GetPrintOption & DefaultPrinterConfig;
const ipcMessage = useIpcSend(TypeKey.print);

class App extends Obverse {
    constructor() {
        super();
        makeObservable(this);
    }

    // 获取打印机列表
    @action.bound
    public fetchPrinterList() {
        this.printerList.loading = true;
        getPrinterList()
            .then((res) => {
                if (res.data.code === 200) {
                    runInAction(() => {
                        this.printerList.result = res.data.result.map(
                            (item: OriginPrint) => ({
                                default: item.default,
                                key: item.printer_name.replace(/\\/g, '%5C'),
                                value: item.printer_name.replace(/\\/g, '%5C')
                            })
                        );
                    });
                } else {
                    message.error('获取打印机列表失败...');
                }
            })
            .finally(() => {
                runInAction(() => {
                    this.printerList.loading = false;
                });
            });
    }

    // 唤醒打印机的SDK服务
    @action.bound
    public awakenPrintService() {
        this.awaken.loading = true;
        return new Promise((resolve) => {
            ipcMessage('open:print')
                .then((result: boolean) => {
                    runInAction(() => {
                        this.awaken.status = result;
                        this.fetchPrinterOption();
                        this.fetchAppCacheDir();
                        this.fetchPrintFileType();
                    });
                })
                .finally(() => {
                    runInAction(() => {
                        this.awaken.loading = false;
                    });
                    resolve(true);
                });
        });
    }

    // 获取打印机参数，包括：（打印机列表）
    @action.bound
    public async fetchPrinterOption(): Promise<unknown> {
        if (!this.awaken.status) return;
        this.fetchPrinterList();
    }

    // 打印文件
    @action.bound
    public async printFile(data: {
        printer: string;
        fileList: Array<unknown>;
        color: string;
    }) {
        runInAction(() => {
            this.printingOption.loading = true;
            this.printingOption.files = data.fileList;
        });
        return printFile({
            ...data,
            fileList: JSON.stringify(this.printingOption.files),
            pageSize: 'A4'
        }).finally(() => {
            runInAction(() => {
                this.printingOption.loading = false;
                this.printingOption.files = [];
            });
        });
    }

    // 清除缓存
    @action.bound
    public async cleanCache() {
        runInAction(() => (this.cleanCacheOption.loading = true));

        return cleanCache().finally(() => {
            runInAction(() => (this.cleanCacheOption.loading = false));
        });
    }

    // 设置程序名称
    @action.bound
    public setAppName(appName: string) {
        this.appName = appName;
    }

    // 设置程序缓存地址
    @action.bound
    public fetchAppCacheDir() {
        this.appCacheDir.loading = true;
        getCachePath()
            .then((res) => {
                if (res.data.code !== 200) throw new Error(res.data.result);
                runInAction(() => {
                    this.appCacheDir.result = { ...res.data.result };
                });
            })
            .catch((e) => {
                message.error('获取程序缓存地址失败：', e.message);
            })
            .finally(() => {
                runInAction(() => (this.appCacheDir.loading = false));
            });
    }

    // 获取主进程支持打印的文件类型
    @action.bound
    public fetchPrintFileType() {
        this.supportPrintFileType.loading = true;
        getSupportPrintType()
            .then((result) => {
                if (result.data.code !== 200)
                    throw new Error(result.data.result);
                runInAction(() => {
                    this.supportPrintFileType.result = result.data.result;
                    ipcMessage(
                        'set:support:print:type',
                        JSON.stringify(this.supportPrintFileType.result)
                    );
                });
            })
            .catch((e) => {
                console.log(e);
                message.error('获取支持的打印文件类型失败：', e.message);
            })
            .finally(() => {
                runInAction(() => (this.supportPrintFileType.loading = false));
            });
    }
}

export default new App();
